<template>
  <div class="document-viewer" :class="{ 'loading': loading, 'fullscreen': isFullscreen }">
    <!-- 顶部工具栏 -->
    <div class="viewer-toolbar" v-if="!loading && !error">
      <div class="toolbar-right">
        <el-tooltip content="全屏预览" placement="top">
          <el-button type="primary" plain size="small" @click="toggleFullscreen">
            <el-icon><FullScreen v-if="!isFullscreen" /><ScaleToOriginal v-else /></el-icon>
            {{ isFullscreen ? '退出全屏' : '全屏' }}
          </el-button>
        </el-tooltip>
      </div>
    </div>
    
    <!-- 加载中 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <!-- 错误提示 -->
    <div v-else-if="error" class="error-container">
      <el-result
        icon="error"
        title="文件加载失败"
        :sub-title="error"
      >
        <template #extra>
          <el-button type="primary" @click="retryLoading">重试</el-button>
        </template>
      </el-result>
    </div>
    
    <!-- 通用文档查看器 -->
    <div v-else-if="isOfficeDocument" class="office-viewer">
      <iframe
        v-if="officeViewerUrl"
        :src="officeViewerUrl"
        class="office-iframe"
        frameborder="0"
        allowfullscreen
      ></iframe>
    </div>
    
    <!-- HTML查看器 -->
    <div v-else-if="documentType === 'html'" class="html-viewer">
      <iframe
        v-if="documentUrl"
        :src="documentUrl"
        class="html-iframe"
        frameborder="0"
        sandbox="allow-same-origin allow-scripts"
      ></iframe>
    </div>
    
    <!-- Markdown查看器 -->
    <div v-else-if="documentType === 'markdown'" class="markdown-viewer">
      <div class="markdown-container" v-html="markdownContent"></div>
    </div>
    
    <!-- 纯文本查看器 -->
    <div v-else-if="documentType === 'text'" class="text-viewer">
      <pre class="text-content">{{ textContent }}</pre>
    </div>
    
    <!-- 不支持的文件类型 -->
    <div v-else class="unsupported-container">
      <el-result
        icon="warning"
        title="不支持的文件类型"
        sub-title="当前文件类型无法预览"
      >
      </el-result>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { marked } from 'marked';
import { getFileContent, getFileType } from '../../utils/dataService';
import { FullScreen, ScaleToOriginal } from '@element-plus/icons-vue';

const props = defineProps({
  // 文档URL
  documentUrl: {
    type: String,
    required: true
  },
  // 文档名称
  documentName: {
    type: String,
    default: ''
  },
  // 文档类型: 'auto', 'pdf', 'word', 'markdown', 'html', 'text', 'presentation', 'spreadsheet'
  documentType: {
    type: String,
    default: 'auto'
  }
});

const emit = defineEmits(['loaded', 'error']);

// 状态管理
const loading = ref(true);
const error = ref('');
const markdownContent = ref('');
const textContent = ref('');
const isFullscreen = ref(false);

// 判断实际的文档类型
const actualDocumentType = computed(() => {
  if (props.documentType !== 'auto') {
    return props.documentType;
  }
  
  return getFileType(props.documentName || props.documentUrl);
});

// 是否为Office文档
const isOfficeDocument = computed(() => {
  const type = actualDocumentType.value;
  return ['pdf', 'word', 'presentation', 'spreadsheet'].includes(type);
});

// Office文档查看器URL
const officeViewerUrl = computed(() => {
  if (!isOfficeDocument.value) return '';
  
  const type = actualDocumentType.value;
  
  // 对于PDF，直接使用浏览器内置查看器
  if (type === 'pdf') {
    console.log('DocumentViewer: 使用浏览器内置PDF查看器:', props.documentUrl);
    return props.documentUrl;
  }
  
  // 对于其他Office文档，使用Microsoft Office Online Viewer
  const encodedUrl = encodeURIComponent(props.documentUrl);
  console.log('DocumentViewer: 使用Office Online查看器:', props.documentUrl);
  return `https://view.officeapps.live.com/op/embed.aspx?src=${encodedUrl}`;
});

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
  
  if (isFullscreen.value) {
    document.body.classList.add('viewer-fullscreen-active');
  } else {
    document.body.classList.remove('viewer-fullscreen-active');
  }
};

// 监听ESC键退出全屏
const handleKeyDown = (e) => {
  if (e.key === 'Escape' && isFullscreen.value) {
    toggleFullscreen();
  }
};

// 加载文档
const loadDocument = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    // 判断文档类型
    const docType = actualDocumentType.value;
    console.log('加载文档:', props.documentUrl, '类型:', docType);
    
    // 根据文档类型加载不同的内容
    if (docType === 'markdown') {
      await loadMarkdownDocument();
    } else if (docType === 'text') {
      await loadTextDocument();
    } else if (['pdf', 'word', 'presentation', 'spreadsheet', 'html'].includes(docType)) {
      // 这些类型通过iframe直接加载，无需额外处理
      loading.value = false;
    } else {
      throw new Error('不支持的文件类型');
    }
    
    emit('loaded', { type: docType });
  } catch (err) {
    console.error('加载文档失败:', err);
    error.value = err.message || '无法加载文档，请稍后重试';
    emit('error', { error: err.message });
  } finally {
    loading.value = false;
  }
};

// 加载Markdown文档
const loadMarkdownDocument = async () => {
  try {
    // 尝试使用标准模式
    const response = await fetch(props.documentUrl);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const text = await response.text();
    
    // 使用marked库解析Markdown
    markdownContent.value = marked(text, { 
      breaks: true, 
      gfm: true
    });
  } catch (err) {
    console.error('标准模式加载Markdown文档失败:', err);
    
    try {
      // 尝试使用no-cors模式
      console.log('尝试使用no-cors模式加载文件');
      const response = await fetch(props.documentUrl, { mode: 'no-cors' });
      const text = await response.text();
      
      // 使用marked库解析Markdown
      markdownContent.value = marked(text, { 
        breaks: true, 
        gfm: true
      });
    } catch (nocorsError) {
      console.error('no-cors模式加载Markdown文档也失败:', nocorsError);
      
      // 如果是CORS错误，显示友好的错误信息
      if (err.toString().includes('CORS')) {
        markdownContent.value = marked(`# 无法加载文件内容

由于跨域限制，无法直接加载文件内容。请尝试以下方法：

1. 下载文件后在本地查看
2. 联系管理员配置正确的CORS头

文件路径: ${props.documentUrl}`, { breaks: true, gfm: true });
      } else {
        throw new Error('无法加载Markdown文档，请重试');
      }
    }
  }
};

// 加载文本文档
const loadTextDocument = async () => {
  try {
    // 尝试使用标准模式
    const response = await fetch(props.documentUrl);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    textContent.value = await response.text();
  } catch (err) {
    console.error('标准模式加载文本文档失败:', err);
    
    try {
      // 尝试使用no-cors模式
      console.log('尝试使用no-cors模式加载文件');
      const response = await fetch(props.documentUrl, { mode: 'no-cors' });
      textContent.value = await response.text();
    } catch (nocorsError) {
      console.error('no-cors模式加载文本文档也失败:', nocorsError);
      
      // 如果是CORS错误，显示友好的错误信息
      if (err.toString().includes('CORS')) {
        textContent.value = `无法加载文件内容

由于跨域限制，无法直接加载文件内容。请尝试以下方法：

1. 下载文件后在本地查看
2. 联系管理员配置正确的CORS头

文件路径: ${props.documentUrl}`;
      } else {
        throw new Error('无法加载文本内容，请重试');
      }
    }
  }
};

// 重试加载
const retryLoading = () => {
  loadDocument();
};

// 监听文档URL变化
watch(() => props.documentUrl, (newUrl) => {
  if (newUrl) {
    loadDocument();
  }
});

// 初始化
onMounted(() => {
  if (props.documentUrl) {
    loadDocument();
  }
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeyDown);
});

// 组件卸载
onUnmounted(() => {
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyDown);
  // 确保退出全屏状态
  if (isFullscreen.value) {
    document.body.classList.remove('viewer-fullscreen-active');
  }
});
</script>

<style scoped>
.document-viewer {
  height: 100%;
  width: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

/* 全屏模式 */
.document-viewer.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  border-radius: 0;
}

/* 工具栏 */
.viewer-toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 8px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e5e7eb;
}

.toolbar-right {
  display: flex;
  gap: 8px;
  align-items: center;
}

.loading-container {
  padding: 24px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.error-container,
.unsupported-container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Office文档查看器样式 */
.office-viewer {
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  background-color: #f0f0f0;
}

.office-iframe {
  height: 100%;
  width: 100%;
  border: none;
  background-color: white;
}

/* HTML查看器样式 */
.html-viewer {
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  background-color: #f0f0f0;
}

.html-iframe {
  height: 100%;
  width: 100%;
  border: none;
  background-color: white;
}

/* Markdown查看器样式 */
.markdown-viewer {
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  background-color: #f0f0f0;
}

.markdown-container {
  max-width: 100%;
  padding: 20px;
  line-height: 1.6;
  background-color: white;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

/* 纯文本查看器样式 */
.text-viewer {
  flex: 1;
  overflow: auto;
  display: flex;
  justify-content: center;
  background-color: #f0f0f0;
}

.text-content {
  font-family: monospace;
  white-space: pre-wrap;
  margin: 0;
  padding: 20px;
  background-color: white;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  width: 100%;
}

/* 全局样式 - 需要在main.js中导入 */
:global(.viewer-fullscreen-active) {
  overflow: hidden !important;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .viewer-toolbar {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .toolbar-right {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 